#include "registerCommand.h"

QDomDocument RegisterCommand::run(QDomDocument doc) {
    QDomDocument xmlDocument;
    QString result = "<register><success>FALSE</success>";
    bool success = true;

    QDomNodeList loginNodes = doc.elementsByTagName("login");
    QDomNodeList passHashNodes = doc.elementsByTagName("passHash");
    if (loginNodes.count() == 1 && passHashNodes.count() == 1) {
        QString login = loginNodes.at(0).toElement().text().trimmed();
        QString passHash = passHashNodes.at(0).toElement().text().trimmed();
        if (!this->isLoginCorrect(login)) {
            result.append("<reason>WRONG_LOGIN_CHARS</reason>");
            success = false;
        }
        if (!this->isHashCorrect(passHash)) {
            result.append("<reason>WRONG_PASS_CHARS</reason>");
            success = false;
        }
        if (success) {
            if (DB::getInstance()->findByLogin(login) == NULL) {
                User* user = new User(login, passHash);
                DB::getInstance()->addUser(user);
                result = "<register><success>TRUE</success></register>";
            } else {
                result.append("<reason>LOGIN_EXISTS</reason>");
                success = false;
            }
        }
    } else {
        result.append("<reason>WRONG_XML</reason>");
    }

    if (!success) {
        result.append("</register>");
    }

    xmlDocument.setContent(result);
    return xmlDocument;
}

